package com.frogs.ucenter.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.base.web.BaseController3;
import com.frogs.framework.util.DWZResponse;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.RenderUtil;
import com.frogs.framework.util.StringUtil;
import com.frogs.framework.web.HttpRequestInfo;
import com.frogs.system.util.ApiUrlParamEnum;
import com.frogs.ucenter.component.RequestApiHelper;
import com.frogs.ucenter.entity.AreaInfo;
import com.frogs.ucenter.service.AreaInfoService;

@Controller
@RequestMapping("/admin/areaInfo")
public class AreaInfoController extends BaseController3 {
    private static final String ROOT_VIEW = "admin/areaInfo";

    private static final String HOME_VIEW = "admin/areaInfo/home";

    private static final String EDIT_VIEW = "admin/areaInfo/edit";
    
    private static final String SUB_LIST = "/sub";

    @Autowired
    private AreaInfoService areaInfoService;
    
    @Resource
    private RequestApiHelper apiHelper;

    @RequestMapping()
    public String listAreaInfo(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap( request, model, true );
//        String eqProvince = reqInfo.getParameter("eqProvince", "");
//        String eqCity = reqInfo.getParameter("eqCity", "");
//        String eqDistrict = reqInfo.getParameter("eqDistrict", "");
//        if (!StringUtil.isEmpty(eqDistrict)) {
//        } else if (!StringUtil.isEmpty(eqCity)) {
//        	model.put("groupByClause", "district");
//        } else if (!StringUtil.isEmpty(eqProvince)) {
//        	model.put("groupByClause", "city, district");
//        }
        getPageList( model );
        return HOME_VIEW;
    }

    @RequestMapping(EDIT)
    public String createAreaInfo(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap( request, model, false );
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
            model.put( "model",areaInfoService.getById( id ) ); 
        }
        return EDIT_VIEW;
    }
    
    @RequestMapping(SUB_LIST)
    public List<Map<String, String>> subAreaInfo(HttpServletRequest request, ModelMap model) {
    	HttpRequestInfo reqInfo = new HttpRequestInfo(request);
    	String parentId = reqInfo.getParameter(ApiUrlParamEnum.parentId.getParamName(),"0");
    	try {
			return areaInfoService.getSubAreaList(parentId);
		} catch (Exception e) {
			return null;
		}
    }

    @RequestMapping(ADD)
    public String saveAreaInfo(HttpServletRequest request, HttpServletResponse response, ModelMap model, AreaInfo areaInfo) {
        setRequestModelMap(request, model, false);
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String cityCode = reqInfo.getParameter("cityCode", "");
        String districtCode = reqInfo.getParameter("districtCode", "");
        DWZResponse.Builder builder;
        try {
        	String areaId = "";
        	if (StringUtil.isEmpty(districtCode)) {
        		String parentId = cityCode;
        		List<Map<String, String>> list = areaInfoService.getSubAreaList(parentId);
        		if (list.size() > 0) {
        			Map<String, String> area = list.get(list.size() -1);
        			String areaCode = area.get("areaCode");
        			areaId = String.valueOf((Integer.valueOf(areaCode) + 1));
        		} else {
        			areaId = parentId + "01";
        		}
        	} else {
        		areaId = cityCode + districtCode;
        	}
        	areaInfo.setAreaId(areaId);
        	areaInfo.setStreet(areaInfo.getProvince() + areaInfo.getCity() + areaInfo.getDistrict());
            areaInfoService.insert( areaInfo ); 
            builder = DWZResponse.getSucessBuilder("success");
        } catch (Exception e) {
            builder = DWZResponse.getFailBuilder("fail" + e.getMessage());
        }
        RenderUtil.renderHtml(builder.build().toString(), response);
        return null;
    }

    @RequestMapping(SHOW)
    public String showAreaInfo(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
            model.addAttribute( areaInfoService.getById( id ) ); 
        }
        setRequestModelMap(request, model);
        return null;
    }

    @RequestMapping(UPDATE)
    public String updateAreaInfo(HttpServletRequest request, HttpServletResponse response, ModelMap model, AreaInfo areaInfoNew) throws Exception {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
            DWZResponse.Builder builder;
            try {
                AreaInfo areaInfo = areaInfoService.getById( id );
                Map<String, Object> param = new HashMap<String, Object>();
                param.put("street", areaInfoNew.getProvince() + areaInfoNew.getCity() + areaInfoNew.getDistrict());
                // 修改了省级
                if (!areaInfo.getProvince().equals(areaInfoNew.getProvince())) {
                	param.put("likeAreaId", areaInfo.getAreaId().substring(0, 2));
                	param.put("province", areaInfoNew.getProvince());
                	areaInfoService.update(param);
                }
                // 修改了市级
                if (!areaInfo.getCity().equals(areaInfoNew.getCity())) {
                	param.put("likeAreaId", areaInfo.getAreaId().substring(0, 4));
                	param.put("city", areaInfoNew.getCity());
                	areaInfoService.update(param);
                }
                // 修改了地区
                if (!areaInfo.getDistrict().equals(areaInfoNew.getDistrict())) {
                	param.put("likeAreaId", areaInfo.getAreaId().substring(0, 6));
                	param.put("district", areaInfoNew.getDistrict());
                	areaInfoService.update(param);
                }
                
                PropertyUtils.copyProperties(areaInfo, areaInfoNew);
                
                areaInfo.setStreet(areaInfo.getProvince() + areaInfo.getCity() + areaInfo.getDistrict());
                areaInfoService.update( areaInfo ); 
                model.clear();
                builder = DWZResponse.getSucessBuilder("success");
            } catch (Exception e) {
                builder = DWZResponse.getFailBuilder("fail" + e.getMessage());
            }
            RenderUtil.renderHtml(builder.build().toString(), response);
        }
        return null;
    }
    
    @RequestMapping(DELETE)
    public String deleteAreaInfo(HttpServletRequest request, HttpServletResponse response, ModelMap model, String inIdList) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap(request, model);
        DWZResponse.Builder builder;
        try {
            String[] idArray = inIdList.split(",");
            model.put("inIdList", idArray);
            areaInfoService.delete( model ); 
            builder = DWZResponse.getSucessBuilder("删除成功");
        } catch (Exception e) {
            builder = DWZResponse.getFailBuilder("删除失败" + e.getMessage());
        }
        RenderUtil.renderHtml(builder.build().toString(), response);
        model.clear();
        return null;
    }

    private PageList<AreaInfo> getPageList(ModelMap model) {
        PageList<AreaInfo> areaInfoList = areaInfoService.getList( model, Integer.parseInt(model.get("pageNum").toString()), Integer.parseInt(model.get("numPerPage").toString()) ); 
        model.put("areaInfoList",areaInfoList);
        model.put("pageTurn",areaInfoList.getPageTurn());
        return areaInfoList;
    }
    
    @RequestMapping("/getSubArea")
    public Map<String, Object> getSubAreaInfo(ModelMap model, String parentId) throws Exception {
    	Map<String, Object> result = new HashMap<String, Object>();
    	List<Map<String, String>> list = areaInfoService.getSubAreaList(parentId);
    	result.put("areaInfo", list);
    	return result;
    }
    
    @RequestMapping("/createJs")
    public JSONObject createJs() {
    	return apiHelper.creatAreaJs();
    }
}